<?php
/**
 * yiyuan_user 模型
 * @authors xiadx (xiadx@zpdchina.com)
 * @date    2017-03-03 18:56:12
 * @version $Id$
 */

class YiyuanUserModel extends BaseModel {

    public function departmentPosition($user_number, $user_department)
    {
		$query = DB::select('zpd_department_position,user_department_position')
				->from('yiyuan_user')
				->where_open()
					->where_open()
						->or_where('user_department', '=', $user_department)
						->and_where('zpd_department', 'is', null)
					->where_close()
					->or_where('zpd_department', '=', $user_department)
				->where_close()
				->and_where('user_number', '=', $user_number)
				->execute()
				->offsetGet(0);
	    return $query;
    }

    public function ls($user_department='')
    {
    	/*M("yiyuan_user")->where("user_type = '护士' and ((user_department = '$user_department' and zpd_department is null) or zpd_department = '$user_department')")->field("id,user_number,user_name,login_password")->select();*/
    	$query = DB::select('id,user_number,user_name,login_password')
    				->from('yiyuan_user')
    				->where('yiyuan_id', '=', $this->yiyuan_id)
    				->and_where('user_type', '=', '护士')
    				->and_where_open()
    					->where_open()
    						->where('user_department', '=', $user_department)
    						->and_where('zpd_department', 'IS', NULL)
						->where_close()
						->or_where('zpd_department', '=', $user_department)
					->and_where_close()
					->execute()
					->as_array();
		return $query;
    }


    /**
     *保存session;
     */
    public function _after_asyncWithServerLogin($user_department,$user_department_id)
    {
        $session=Yaf_Session::getInstance();
        $sessionID = $session->session_id;
        $user_number = $session->user_number;
        $shebei_id = $session->shebei_id;
        if($user_number && $sessionID){
        	$sess_data = array('user_number'=>$user_number,
        			'sesskey'=>$sessionID,
        			'expiry'=>time()+180,
        			'login_state'=>1,
        			'shebei_id'=>$shebei_id,
        			'yiyuan_id'=>$this->yiyuan_id,
        			'user_department'=>$user_department,
        			'user_department_id'=>$user_department_id,
        	);
        	$insert = DB::insert('yiyuan_sess')
        	->columns(array_keys($sess_data))
        	->values(array_values($sess_data));
        	list($insert_id, $affected_rows) = $insert->execute();
        }
        
    }

    //判断是否可以登录
    public function checkOnceLogin($session_id,$user_department,$user_department_id)
    {
        $now = time();//失效时间
        $session=Yaf_Session::getInstance();
        $user_number = $session->user_number;
        $shebei_id = $session->shebei_id;

        //获取医院id
        $yiyuan_id = $this->yiyuan_id;
        $sess = DB::select("id","user_number","sesskey","expiry","shebei_id","login_state","user_department_id")
            ->from("yiyuan_sess")
            ->where("user_number","=",$user_number)
            ->and_where("expiry",">=",$now)
            ->order_by("expiry","DESC")
            ->execute()
            ->offsetGet(0);

        if(Yaconf::get("config$yiyuan_id.allow_multi_window") == '1')//严格单用户登录
        {
            if(!empty($sess) && $sess['shebei_id'] != $shebei_id){
                if($_REQUEST['user_department_id']){//退出前一台的同一登录用户
                    $is_ok = Utility::pushMsg($user_number, $_REQUEST['user_department_id'], '当前登录账号已在其他终端登陆，被迫下线！', 0, 'logout', rand(),$yiyuan_id);
                }
                //生成session_id
                DB::delete('yiyuan_sess')
                    ->where('user_number', '=', $user_number)
                    ->and_where("yiyuan_id","=", $yiyuan_id)
                    ->where('expiry', '<', $now)
                    ->execute();
            }elseif (!empty($sess) && $sess['shebei_id'] == $shebei_id)//单账户登录切换科室，更新科室
            {
                $isexist_user_department_id = DB::select("user_department_id")
                    ->from("yiyuan_sess")
                    ->where("user_number","=",$user_number)
                    ->and_where("user_department_id","=",$_REQUEST['user_department_id'])
                    ->execute()
                    ->get("user_department_id",0);

                if($_REQUEST['user_department_id'] == $isexist_user_department_id)
                {
                    if($_REQUEST['user_department_id']){//退出前一台的同一登录用户
                        $is_ok = Utility::pushMsg($user_number, $_REQUEST['user_department_id'], '当前登录账号已在其他终端登陆，被迫下线！', 0, 'logout', rand(),$yiyuan_id);
                    }
                    //生成session_id
                    DB::delete('yiyuan_sess')
                        ->where('user_number', '=', $user_number)
                        ->and_where("yiyuan_id","=", $yiyuan_id)
                        ->where('expiry', '<', $now)
                        ->execute();
                }
                if($sess['sesskey'] == $session_id)//更新科室
                {
                    $expirytime = $now + 180;
                    $update_arr = array(
                        "expiry"=>$expirytime,
                        "user_department"=>$user_department,
                        "user_department_id"=>$user_department_id,
                    );
                    DB::update('yiyuan_sess')
                        ->set($update_arr)
                        ->where('sesskey','=',$session_id)
                        ->where('yiyuan_id', '=', $this->yiyuan_id)
                        ->execute();
                    return 1;
                }
            }
        }elseif (Yaconf::get("config$yiyuan_id.allow_multi_window") == '2')//单用户单科室登录
        {
            if(!empty($sess) && ($sess['shebei_id'] != $shebei_id))
            {
                $isexist_user_department_id = DB::select("user_department_id")
                ->from("yiyuan_sess")
                ->where("user_number","=",$user_number)
                ->and_where("user_department_id","=",$_REQUEST['user_department_id'])
                ->execute()
                ->get("user_department_id",0);

                if($_REQUEST['user_department_id'] == $isexist_user_department_id)
                {
                    if($_REQUEST['user_department_id']){//退出前一台的同一登录用户
                        $is_ok = Utility::pushMsg($user_number, $_REQUEST['user_department_id'], '当前登录账号已在其他终端登陆，被迫下线！', 0, 'logout', rand(),$yiyuan_id);
                    }
                    //生成session_id
                    DB::delete('yiyuan_sess')
                        ->where('user_number', '=', $user_number)
                        ->and_where("yiyuan_id","=", $yiyuan_id)
                        ->where('expiry', '<', $now)
                        ->execute();
                }
            }elseif (!empty($sess) && $sess['shebei_id'] == $shebei_id)
            {
                $isexist_user_department_id = DB::select("user_department_id")
                ->from("yiyuan_sess")
                ->where("user_number","=",$user_number)
                ->and_where("user_department_id","=",$_REQUEST['user_department_id'])
                ->execute()
                ->get("user_department_id",0);
                if($_REQUEST['user_department_id'] == $isexist_user_department_id)
                {
                    if($_REQUEST['user_department_id']){//退出前一台的同一登录用户
                        $is_ok = Utility::pushMsg($user_number, $_REQUEST['user_department_id'], '当前登录账号已在其他终端登陆，被迫下线！', 0, 'logout', rand(),$yiyuan_id);
                    }
                    //生成session_id
                    DB::delete('yiyuan_sess')
                        ->where('user_number', '=', $user_number)
                        ->and_where("yiyuan_id","=", $yiyuan_id)
                        ->where('expiry', '<', $now)
                        ->execute();
                }
                if($sess['sesskey'] == $session_id)//更新科室
                {
                    if($isexist_user_department_id)
                    {
                        if($_REQUEST['user_department_id']){//退出前一台的同一登录用户
                            $is_ok = Utility::pushMsg($user_number, $_REQUEST['user_department_id'], '当前登录账号已在其他终端登陆，被迫下线！', 0, 'logout', rand(),$yiyuan_id);

                        }
                        //生成session_id
                        DB::delete('yiyuan_sess')
                            ->where('user_number', '=', $user_number)
                            ->and_where("yiyuan_id","=", $yiyuan_id)
                            ->where('expiry', '<', $now)
                            ->execute();
                    }
                    $expirytime = $now + 180;
                    $update_arr = array(
                        "expiry"=>$expirytime,
                        "user_department"=>$user_department,
                        "user_department_id"=>$user_department_id,
                    );
                    DB::update('yiyuan_sess')
                        ->set($update_arr)
                        ->where('sesskey','=',$session_id)
                        ->where('yiyuan_id', '=', $this->yiyuan_id)
                        ->execute();
                    return 1;
                }
            }
        }
        else//单账户可以多终端登录
        {
            if(!empty($sess)&&($sess['shebei_id'] == $shebei_id)&&($sess['sesskey'] == $session_id))//更新科室
            {
                $expirytime = $now + 180;
                $update_arr = array(
                    "expiry"=>$expirytime,
                    "user_department"=>$user_department,
                    "user_department_id"=>$user_department_id,
                );
                DB::update('yiyuan_sess')
                    ->set($update_arr)
                    ->where('id','=',$session_id)
                    ->where('yiyuan_id', '=', $this->yiyuan_id)
                    ->execute();
                return 1;
            }
        }
        return "";
    }

    public function sendNewYizhu($hushi_id,$user_department)
    {
        $zhuyuan_mod = new ZhuyuanBasicInfoModel;
        $zhuyuan_basic_info = $zhuyuan_mod->getZhyuanIdList($user_department);
        $zhuyuan_ids = Utility::array_pluck($zhuyuan_basic_info, 'zhuyuan_id');

        //获取当天已读的组号
        $yizhu_yidu_info = $this->getYiduZuhao($hushi_id);
        $zuhaos = Utility::array_pluck($yizhu_yidu_info, 'zuhao');
        $content = "";
        $data = $this->getnewyizhu($zhuyuan_ids,$zuhaos);
        $tixing_mod = new ZhuyuanYizhuTixingInfoModel;
        $field_arr = $tixing_mod->_field_arr;
        foreach ($data as $k => $value) {
            if ($k == 0) {
                $content = sprintf("REPLACE INTO xinyizhu_tixing_info (yizhu_id,zhuyuan_id,yizhu_type,content,start_time,yongfa,yongliang,shiyong_danwei,pinlv,zuhao,yongfa_type,zhixing_state,state,wancheng_cishu) SELECT '%s', '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s' ",
                    $value["yizhu_id"],
                    $value["zhuyuan_id"],
                    $value["yizhu_type"],
                    $value["content"],
                    $value["start_time"],
                    $value["yongfa"],
                    $value["yongliang"],
                    $value["shiyong_danwei"],
                    $value["pinlv"],
                    $value["zuhao"],
                    $value["yongfa_type"],
                    $value["zhixing_state"],
                    $value["state"],
                    $value["wancheng_cishu"]
                );
            } else {
                $content .= sprintf(" UNION ALL SELECT '%s', '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s'",
                    $value["yizhu_id"],
                    $value["zhuyuan_id"],
                    $value["yizhu_type"],
                    $value["content"],
                    $value["start_time"],
                    $value["yongfa"],
                    $value["yongliang"],
                    $value["shiyong_danwei"],
                    $value["pinlv"],
                    $value["zuhao"],
                    $value["yongfa_type"],
                    $value["zhixing_state"],
                    $value["state"],
                    $value["wancheng_cishu"]
                );
            }

        }
        $is_ok = Utility::pushMsg($hushi_id, $user_department, $content, 0, 'xin_yizhu', rand(),0);
    }


    public function getnewyizhu($zhuyuan_ids =[],$zuhao=[])
    {
        if (empty($zhuyuan_ids)) {
            return [];
        }
        $zhuyuan_ids_str = "";
        foreach ($zhuyuan_ids as $item)
        {
            if($zhuyuan_ids_str)
            {
                $zhuyuan_ids_str .= ",'".$item."'";
            }else{
                $zhuyuan_ids_str = "'".$item."'";
            }
        }
        $zuhao_ids = "";
        if(!empty($zuhao))
        {
            foreach ($zuhao as $key=>$item)
            {
                $zuhao[$key] = "'".$item."'";
            }
            $zuhao_ids = implode(",",$zuhao);
        }
        $set = Yaconf::get("config$this->yiyuan_id.xinyizhu_tixing_delete");
        $field = 'yizhu_id,zhuyuan_id,yizhu_type,content,start_time,yongfa,yongliang,shiyong_danwei,pinlv,zuhao,yongfa_type,zhixing_state,state,wancheng_cishu';

        $temp = "select $field from zhuyuan_yizhu_tixing_info where zhuyuan_id in ($zhuyuan_ids_str) AND 
        yiyuan_id=0";
        if(!empty($zuhao_ids))
        {
            $temp .= " and zuhao not in ($zuhao_ids)";
        }
        if($set['state'] == 'on')
        {
            $temp .= " and start_time > DATE_SUB(now(),INTERVAL ".($set['value'] ?: 30)." MINUTE)";
        }
        $query =  DB::query(Database::SELECT, $temp)->execute()->as_array();

        return $query;
    }

    public function getYiduZuhao($hushi_id)
    {
        $temp_int_time = strtotime(date("Y-m-d"));
        $data = DB::select("*")
            ->from("zhuyuan_yizhu_tixing_info_yidu")
            ->where("user_number","=",$hushi_id)
            ->and_where("addtime",">",$temp_int_time)
            ->execute()
            ->as_array();
        return $data;
    }


}
